package handler

import (
	"context"
	"fmt"
	"zg4/zk1/server/global"
	"zg4/zk1/server/model"
	__ "zg4/zk1/server/proto"
)

type Server struct {
	__.UnimplementedVideoServer
}

func (s *Server) UserLogin(_ context.Context, req *__.UserLoginRequest) (*__.UserLoginResponse, error) {

	var user model.User
	global.DB.Debug().Where("account = ?", req.Account).Find(&user)
	if user.Id == 0 {
		return nil, fmt.Errorf("用户不存在")
	}
	if user.Password != req.Password {
		return nil, fmt.Errorf("用户密码错误")
	}
	return &__.UserLoginResponse{
		UserId: int64(user.Id),
	}, nil
}
func (s *Server) AddVideo(_ context.Context, req *__.AddVideoRequest) (*__.AddVideoResponse, error) {

	video := model.Video{
		Name:   req.Name,
		Cover:  req.Cover,
		Status: uint(req.Status),
	}
	global.DB.Debug().Create(&video)

	return &__.AddVideoResponse{
		VideoId: int64(video.Id),
	}, nil
}
func (s *Server) VideoInfo(_ context.Context, req *__.VideoInfoRequest) (*__.VideoInfoResponse, error) {
	var video model.Video
	global.DB.Debug().Where("id = ?", req.VideoId).Find(&video)
	if video.Id == 0 {
		return nil, fmt.Errorf("视频不存在")
	}
	return &__.VideoInfoResponse{
		VideoId: int64(video.Id),
		Name:    video.Name,
		Cover:   video.Cover,
		Status:  int64(video.Status),
	}, nil
}
func (s *Server) RecommendVideoList(_ context.Context, req *__.RecommendVideoListRequest) (*__.RecommendVideoListResponse, error) {
	page := req.Page
	if page <= 0 {
		page = 1
	}

	pageSize := req.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var videoList []model.Video
	global.DB.Debug().Where("status = ?", 1).Offset(int(offset)).Limit(int(pageSize)).Find(&videoList)

	var list []*__.RecommendVideoList
	for _, v := range videoList {
		list = append(list, &__.RecommendVideoList{
			VideoId: int64(v.Id),
			Name:    v.Name,
			Cover:   v.Cover,
			Status:  int64(v.Status),
		})
	}

	return &__.RecommendVideoListResponse{
		List: list,
	}, nil
}
